// 上传文件可以使用formidable

const http = require('http')
const formidable = require('formidable')

const server = http.createServer(function(req,res){
    console.log(req.headers['content-type'])
    switch(req.method){
        case  'GET':
            show(req,res)
            break;
        case 'POST':
            upload(req,res)
            break
        default:
            res.end('Internet Server Error')
    }
})

server.listen(3000)

function show(req,res){
    const html = "<html><head><title>Todo List</title></head><body><form method='post' action='/' enctype='multipart/form-data'>"
                +'<p><input type="text" name="name"></p>'
                +'<p><input type="file" name="name"></p>'
                +'<p><input type="submit" value="upload"></p>'
                +'</form></body></html>'
    res.setHeader('Content-Type','text/html')
    res.setHeader('Content-Type',Buffer.byteLength(html))
    res.end(html)
}

function upload(req,res){
    if(!isFormData(req)){
        res.statusCode = 400
        res.end('Bad Request:expecting multipart/form-data')
        return
    }
    const form = new formidable.IncomingForm()
    // form.parse(req)

    // form.on('field',function(field,value){
    //     console.log(field+'--------')
    //     console.log(value+'}}}}}}}}}')
    // })

    // form.on('file',function(name,file){
    //     console.log(name+'~~~~~~~')
    //     console.log(file+'+++++++')
    // })

    // form.on('end',function(){
    //     res.end('upload complete')
    // })


    // form.parse(req)
    form.on('progress',function(bytesReceived,bytesExpected){
        const percent = Math.floor(bytesReceived/bytesExpected * 100)
        console.log(percent+'??????????????/')
    })
    form.parse(req,function(err,fields,files){
        console.log(fields)
        console.log(files)
        res.end('upload complete')
    })

    
}

function isFormData(req){
    const type = req.headers['content-type']||''
    return 0 == type.indexOf('multipart/form-data')
}